package com.njtech.pet.interceptor;

import com.njtech.pet.constant.Constant;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author lxj
 * Date 2020-05-23 10:24
 * Description <描述>
 */
public class BasePreHandleInteceptor {
    boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,String roleRequired) throws Exception {
        //获取session
        HttpSession session = httpServletRequest.getSession();
        List<String> roles = (List<String>) session.getAttribute("powers");
        if (roles == null || roles.size() == 0) {
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/NoPermissions");
            System.err.println("用户没有权限，重定向至" + httpServletRequest.getContextPath() + "/NoPermissions");
            return false;
        }
        for (String role :
                roles) {
            if (roleRequired.equals(role)) {
                return true;
            }
        }
        httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/NoPermissions");
        System.err.println("未检测到管理员权限，重定向至" + httpServletRequest.getContextPath() + "/NoPermissions");
        return false;
    }
}
